/**
 * OFD转PDF
 */
layui.define(['table', 'form', 'dropdown', 'util'], function (exports) {
    var $ = layui.$
        , admin = layui.admin
        , setter = layui.setter
        , view = layui.view
        , table = layui.table
        , form = layui.form
        , dropdown = layui.dropdown
        , upload = layui.upload
        , util = layui.util
        , element = layui.element;

    let atOnceUploadFileMaxNumber, singleFileMaxLength, isEnablePapaerInvoice;

    function isJsonStringEmpty(jsonString) {
        // 首先，检查字符串是否为null或空字符串  
        if (jsonString === null || jsonString === "" || jsonString.trim() === "") {
            return true;
        }

        // 尝试将字符串解析为JSON  
        try {
            const parsed = JSON.parse(jsonString);

            // 检查是否为空对象或空数组  
            if (Array.isArray(parsed) && parsed.length === 0) {
                return true;
            }
            if (typeof parsed === 'object' && parsed !== null && Object.keys(parsed).length === 0) {
                return true;
            }

            // 如果不是空对象或空数组，则认为字符串不是空的  
            return false;
        } catch (e) {
            // 如果解析出错，则不是有效的JSON字符串，这里可以根据需求返回false或抛出错误  
            // 这里我们简单返回false，表示它不是空的（因为我们只关心空的情况）  
            return false;
        }

        // 理论上，如果字符串是有效的JSON但不符合上述空的条件，这里不会执行  
        // 但为了代码的完整性，我们可以显式地返回一个false（尽管上面的catch块已经处理了所有情况）  
        return false;
    }

    function addLog(logObj) {
        $.ajax({
            url: setter.baseConfig.apiHost + '/api/log/add' //实际使用请改成服务端真实接口
            , type: 'post'
            , contentType: "application/json"
            , data: JSON.stringify(logObj)
            , beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
            }
            , success: function (res) {
                if (res.errorCode != '00000') {
                    //layer.msg(res.errorMessage, {
                    //    offset: '15px'
                    //    , icon: 2
                    //    , time: 3000
                    //});

                    return false;
                }
            }
        });
    }

    function getWebSiteConfig() {
        $.ajax({
            url: setter.baseConfig.apiHost + '/api/system/getwebsiteconfig' //实际使用请改成服务端真实接口
            , type: 'post'
            , contentType: "application/json"
            , async: false // 设置为同步请求，确保能实时获取到网站配置
            //, data: JSON.stringify(data)
            , beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
            }
            , success: function (res) {
                console.log(res);
                if (res.errorCode != '00000') {
                    layer.msg(res.errorMessage, {
                        offset: '15px'
                        , icon: 2
                        , time: 3000
                    });

                    return false;
                }

                atOnceUploadFileMaxNumber = Number(res.data.atOnceUploadFileMaxNumber);
                singleFileMaxLength = Number(res.data.singleFileMaxLength);
                isEnablePapaerInvoice = res.data.isEnablePapaerInvoice === 'on';
            }
        });
    }

    function customAlertTip(content) {
        layer.alert(content, {
            time: 5 * 1000,
            offset: 'auto',
            anim: 'slideDown',
            success: function (layero, index) {
                var timeNum = this.time / 1000, setText = function (start) {
                    layer.title('<span class="layui-font-red">' + (start ? timeNum : --timeNum) + '</span> 秒后自动关闭', index);
                };
                setText(!0);
                this.timer = setInterval(setText, 1000);
                if (timeNum <= 0) clearInterval(this.timer);
            },
            end: function () {
                clearInterval(this.timer);
            }
        });
    }

    //获取网站设置
    getWebSiteConfig();

    //OFD转PDF
    setTimeout(function () {
        table.render({
            elem: '#LAY-convert-ofdtopdf-manage'
            , url: setter.baseConfig.apiHost + '/api/convert/getpagingtopdfs'
            , where: { invoiceType: $('#ID-select-convert-ofdtopdf-invoiceType').val(), uploadTimeStart: $('#ID-laydate-start-date-convert-list-uploadtime').val(), uploadTimeEnd: $('#ID-laydate-end-date-convert-list-uploadtime').val() }
            , toolbar: '#toolbarDemo'
            , defaultToolbar: []
            , method: 'post'
            , contentType: "application/json"
            , headers: { //通过 request 头传递
                Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
            }
            , parseData: function (res) { // res 即为原始返回的数据
                return {
                    "code": res.errorCode, // 解析接口状态
                    "msg": res.errorMessage, // 解析提示文本
                    "count": res.data.totalCount, // 解析数据长度
                    "data": res.data.entities // 解析数据列表
                };
            }
            , cols: [[
                { type: 'numbers', fixed: 'left' }
                , { field: 'id', title: 'Id', hide: true }
                , { field: 'uploadTime', title: '上传时间', minWidth: 180 }
                , { field: 'fileName', title: '文件名称', minWidth: 250 }
                , { field: 'isConvertXml', title: '转换XML', width: 90, templet: '#LAY-convert-ofdtopdf-isConvertXmlTpl' }
                , { field: 'invoiceTypeName', title: '票据类型', width: 300, templet: '#LAY-convert-ofdtopdf-billTypeTpl' }
                , { field: 'total', title: '总金额', minWidth: 100 }
                , { field: 'invoiceNumber', title: '发票号码', minWidth: 200 }
                , { field: 'issueDate', title: '开票日期', minWidth: 110 }
                , { field: 'eticketNumber', title: '电子客票号', minWidth: 150 }
                , { field: 'buyerName', title: '购方名称', minWidth: 220 }
                , { field: 'buyerId', title: '购方纳税人识别号', minWidth: 200 }
                , { title: '操作', width: 300, fixed: 'right', toolbar: '#table-useradmin-webuser' }
            ]]
            , page: true
            , limit: 20
            , limits: [10, 20, 30, 40, 50]
            , text: { none: '无数据' }
        });
    });
    
    // 工具栏事件
    table.on('toolbar(LAY-convert-ofdtopdf-manage)', function (obj) {
        var id = obj.config.id;
        var checkStatus = table.checkStatus(id);
        var othis = lay(this);
        switch (obj.event) {
            case 'upload':
                var idxSelectType= admin.popup({
                    title: '选择票据类型'
                    , area: ['50%', '50%']
                    , id: 'LAY-popup-convert-selecttype'
                    , success: function (layero, index) {
                        view(this.id).render('convert/selecttypeinform').done(function () {
                            form.render(null, 'layadmin-convert-selecttypeform');

                            //选择票据类型
                            // select 事件
                            form.on('select(convert-selecttypeform-select-filter)', function (data) {
                                console.log(data);
                                var elem = data.elem; // 获得 select 原始 DOM 对象
                                var value = data.value; // 获得被选中的值
                                var othis = data.othis; // 获得 select 元素被替换后的 jQuery 对象

                                switch (value) {
                                    case '3'://机票行程单
                                        admin.popup({
                                            title: '批量上传发票'
                                            , area: ['80%', '80%']
                                            , id: 'LAY-popup-convert-uploadofdinvoice'
                                            , success: function (layero, index) {
                                                view(this.id).render('convert/uploadofdform', {
                                                    atOnceUploadFileMaxNumber: atOnceUploadFileMaxNumber,
                                                    singleFileMaxLength: singleFileMaxLength / 1024,
                                                    invoiceType:'3'
                                                }).done(function () {
                                                    form.render(null, 'layuiadmin-form-convert-upload-ofdinvoice');

                                                    //开启提交
                                                    form.on('submit(LAY-upload-ofdinvoice-front-submit)', function (data) {
                                                        var field = data.field; //获取提交的字段

                                                        //提交 Ajax 成功后，关闭当前弹层并重载表格
                                                        var postData = $('#hid-convert-upload-ofdinvoice').val();
                                                        if (isJsonStringEmpty(postData)) {
                                                            console.log(postData);
                                                            layer.msg('请先选择和上传文件!');

                                                            //将日志POST到后台便于查看
                                                            let logObj = {
                                                                logType: '2',
                                                                message: postData,
                                                                detail: postData
                                                            };
                                                            addLog(logObj);

                                                            return false;
                                                        }

                                                        //是否转换XML
                                                        let isConvertXml = false;
                                                        isConvertXml = field['arr[convertXml]'] != null && field['arr[convertXml]'] == 'on';

                                                        $.ajax({
                                                            url: setter.baseConfig.apiHost + '/api/convert/submitconvert' //实际使用请改成服务端真实接口
                                                            , type: 'post'
                                                            , contentType: "application/json"
                                                            , data: JSON.stringify({
                                                                data: JSON.parse(postData),
                                                                invoiceType: field.invoiceType,
                                                                isConvertXml: isConvertXml
                                                            })
                                                            , beforeSend: function (xhr) {
                                                                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                                            }
                                                            , success: function (res) {
                                                                if (res.errorCode != '00000') {
                                                                    layer.msg(res.errorMessage, {
                                                                        offset: '15px'
                                                                        , icon: 2
                                                                        , time: 3000
                                                                    });

                                                                    return false;
                                                                }

                                                                //成功提示
                                                                layer.msg('提交转换成功', {
                                                                    offset: '15px'
                                                                    , icon: 1
                                                                    , time: 3000
                                                                });

                                                                layui.table.reload('LAY-convert-ofdtopdf-manage'); //重载表格
                                                                layer.close(index); //执行关闭
                                                                layer.close(idxSelectType); //执行关闭
                                                            }
                                                        });
                                                    });

                                                    // 制作多文件上传表格
                                                    let uploadElectronicFileArr = [];
                                                    let loadElectronicIndex;
                                                    var uploadElectronicListIns = upload.render({
                                                        elem: '#ID-upload-electronic-files',
                                                        elemList: $('#ID-upload-ofdinvoice-files-list'), // 列表元素对象
                                                        url: setter.baseConfig.apiHost + '/api/myinvoice/upload?uploadType=1', //实际使用请改成服务端真实接口
                                                        headers: { Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName] },
                                                        accept: 'file',
                                                        acceptMime: 'application/ofd,application/pdf',
                                                        //exts: 'pdf|ofd|xml',
                                                        multiple: true,
                                                        number: atOnceUploadFileMaxNumber,
                                                        auto: false,
                                                        bindAction: '#ID-upload-ofdinvoice-files-action',
                                                        size: singleFileMaxLength, //单个文件最大1024KB
                                                        choose: function (obj) {
                                                            var that = this;
                                                            var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列
                                                            // 读取本地文件
                                                            obj.preview(function (index, file, result) {
                                                                var tr = $(['<tr id="upload-' + index + '">',
                                                                '<td>' + file.name + '</td>',
                                                                '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>',
                                                                '<td><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>',
                                                                    '<td>',
                                                                    '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
                                                                    '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',
                                                                    '</td>',
                                                                    '</tr>'].join(''));

                                                                // 单个重传
                                                                tr.find('.demo-reload').on('click', function () {
                                                                    obj.upload(index, file);
                                                                });

                                                                // 删除
                                                                tr.find('.demo-delete').on('click', function () {
                                                                    delete files[index]; // 删除对应的文件
                                                                    tr.remove(); // 删除表格行
                                                                    // 清空 input file 值，以免删除后出现同名文件不可选
                                                                    var next = uploadElectronicListIns.config.elem.next();
                                                                    if (next != undefined && next != null && next.length > 0) {
                                                                        uploadElectronicListIns.config.elem.next()[0].value = '';
                                                                    }
                                                                });
                                                                that.elemList.append(tr);
                                                                element.render('progress'); // 渲染新加的进度条组件
                                                            });
                                                        },
                                                        before: function (obj) { // obj 参数同 choose
                                                            loadElectronicIndex = layer.msg('正在上传', {
                                                                icon: 16,
                                                                shade: 0.3,
                                                                time: 0
                                                            });

                                                            // 若返回 false，则表明阻止上传
                                                            /*
                                                            if(true){
                                                              return false;
                                                            }
                                                            */

                                                            //当点击开始上传按钮后先将提交识别按钮置灰，直到全部文件上传完毕
                                                            $('#ID-upload-ofdinvoice-form-submit').addClass('layui-btn-disabled');

                                                        },
                                                        done: function (res, index, upload) { // 成功的回调
                                                            if (res.isSuccess == true) {
                                                                // do something // 比如将 res 返回的图片链接保存到隐藏域
                                                                let item = {
                                                                    fileName: res.data.fileName,
                                                                    ofdFilePath: res.data.filePath
                                                                };
                                                                uploadElectronicFileArr.push(item);
                                                                return;
                                                            }
                                                            this.error(index, upload);
                                                        },
                                                        allDone: function (obj) { // 多文件上传完毕后的状态回调
                                                            console.log(obj);

                                                            //一起将上传的文件保存到隐藏字段中
                                                            let uploadedFilesArrJson = JSON.stringify(uploadElectronicFileArr)
                                                            $('#hid-convert-upload-ofdinvoice').val(uploadedFilesArrJson);

                                                            //当点击开始上传按钮后先将提交识别按钮置灰，直到全部文件上传完毕
                                                            $('#ID-upload-ofdinvoice-form-submit').removeClass('layui-btn-disabled');

                                                            //关闭loading
                                                            layer.close(loadElectronicIndex);
                                                        },
                                                        error: function (index, upload) { // 错误回调
                                                            var that = this;
                                                            var tr = that.elemList.find('tr#upload-' + index);
                                                            var tds = tr.children();
                                                            // 显示重传
                                                            tds.eq(3).find('.demo-reload').removeClass('layui-hide');
                                                        },
                                                        progress: function (n, elem, e, index) { // 注意：index 参数为 layui 2.6.6 新增
                                                            element.progress('progress-demo-' + index, n + '%'); // 执行进度条。n 即为返回的进度百分比
                                                        }
                                                    });
                                                });
                                            }
                                        });
                                        break;
                                }

                            });
                        });
                    }
                });
                break;
            case 'download'://下载文件
                let downloadFormData = {
                    taskName: '下载文件',
                    billType: $('#ID-select-convert-ofdtopdf-invoiceType').val(),
                    invoiceNumber: $(':input[name=invoiceNumber]').val(),
                    eticketNumber: $(':input[name=eticketNumber]').val(),
                    issueDateStart: $('#ID-laydate-start-date-convert-issuedate').val(),
                    issueDateEnd: $('#ID-laydate-end-date-convert-issuedate').val(),
                    uploadTimeStart: $('#ID-laydate-start-date-convert-list-uploadtime').val(),
                    uploadTimeEnd: $('#ID-laydate-end-date-convert-list-uploadtime').val()
                };
                admin.popup({
                    title: '下载文件'
                    , area: ['60%', '60%']
                    , id: 'LAY-popup-convert-ofdtopdf-download'
                    , success: function (layero, index) {
                        view(this.id).render('convert/downloadform', downloadFormData).done(function () {
                            form.render(null, 'layuiadmin-form-convert-download');

                            //开启提交
                            form.on('submit(LAY-convert-download-front-submit)', function (data) {
                                var field = data.field; //获取提交的字段
                                let exportFieldObj = {};
                                let customFileNameArr = [];

                                //参数校验
                                let isCheckIssueDate = field['arr[issueDate]'] != null && field['arr[issueDate]'] == 'on';
                                let isCheckInvoiceNumber = field['arr[invoiceNumber]'] != null && field['arr[invoiceNumber]'] == 'on';
                                let isCheckEticketNumber = field['arr[eticketNumber]'] != null && field['arr[eticketNumber]'] == 'on';
                                let isCheckBuyerName = field['arr[buyerName]'] != null && field['arr[buyerName]'] == 'on';
                                let isCheckTotal = field['arr[total]'] != null && field['arr[total]'] == 'on';

                                //发票号码和电子客票号至少选择一个
                                if (!isCheckInvoiceNumber && !isCheckEticketNumber) {
                                    layer.msg('发票号码和电子客票号至少选择一个!');
                                    return false;
                                }

                                //构造请求
                                exportFieldObj.fileFormat = field.fileFormat;
                                if (isCheckIssueDate) {
                                    customFileNameArr.push('IssueDate');
                                }
                                if (isCheckInvoiceNumber) {
                                    customFileNameArr.push('InvoiceNumber');
                                }
                                if (isCheckEticketNumber) {
                                    customFileNameArr.push('EticketNumber');
                                }
                                if (isCheckBuyerName) {
                                    customFileNameArr.push('BuyerName');
                                }
                                if (isCheckTotal) {
                                    customFileNameArr.push('Total');
                                }
                                exportFieldObj.customFileName = customFileNameArr;
                                field.exportField = exportFieldObj;

                                $.ajax({
                                    url: setter.baseConfig.apiHost + '/api/convert/download' //实际使用请改成服务端真实接口
                                    , type: 'post'
                                    , contentType: "application/json"
                                    , data: JSON.stringify(field)
                                    , beforeSend: function (xhr) {
                                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                    }
                                    , success: function (res) {
                                        if (res.errorCode != '00000') {
                                            layer.msg(res.errorMessage, {
                                                offset: 'auto'
                                                , icon: 2
                                                , time: 3000
                                            });

                                            return false;
                                        }

                                        layer.alert('下载申请已提交，系统已启用离线下载模式，本次下载的数据将展示在【我的-我的下载】中，请注意查收！', {
                                            offset: 'auto'
                                            , icon: 1
                                        });

                                        layui.table.reload('LAY-convert-ofdtopdf-manage'); //重载表格
                                        layer.close(index); //执行关闭
                                    }
                                });
                            });

                            //取消
                            // 普通事件
                            //  2.9+ 版本可省略 attr 参数，默认读取 lay-on
                            util.on({
                                cancelConvertDownloadForm: function () {
                                    console.log(this); // 当前触发事件的 DOM 元素
                                    layer.close(index);
                                }
                            });
                        });
                    }
                });
                break;            
        };
    });

    //工具条
    table.on('tool(LAY-convert-ofdtopdf-manage)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.prompt({
                formType: 1
                , title: '敏感操作，请验证口令'
            }, function (value, index) {
                layer.close(index);

                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    layer.close(index);
                });
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '编辑用户'
                , area: ['500px', '450px']
                , id: 'LAY-popup-myinvoice-batchupload'
                , success: function (layero, index) {
                    view(this.id).render('user/user/userform', data).done(function () {
                        form.render(null, 'layuiadmin-form-useradmin');

                        //提交
                        form.on('submit(LAY-user-front-submit)', function (data) {
                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            $.ajax({
                                url: setter.baseConfig.apiHost + '/api/user/update' //实际使用请改成服务端真实接口
                                , type: 'post'
                                , contentType: "application/json"
                                , data: JSON.stringify(field)
                                , beforeSend: function (xhr) {
                                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                }
                                , success: function (res) {
                                    if (res.errorCode != '00000') {
                                        layer.msg(res.errorMessage, {
                                            offset: '15px'
                                            , icon: 2
                                            , time: 3000
                                        });

                                        return false;
                                    }

                                    //登入成功的提示与跳转
                                    layer.msg('修改成功', {
                                        offset: '15px'
                                        , icon: 1
                                        , time: 3000
                                    });

                                    layui.table.reload('LAY-myinvoice-manage'); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            });
                        });
                    });
                }
            });
        } else if (obj.event === 'disable') {
            layer.confirm('确定要禁用吗？', function (index) {
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                $.ajax({
                    url: setter.baseConfig.apiHost + '/api/user/disableuser' //实际使用请改成服务端真实接口
                    , type: 'post'
                    , contentType: "application/json"
                    , data: JSON.stringify({
                        id: data.id,
                        isEnabled: 'N'
                    })
                    , beforeSend: function (xhr) {
                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                    }
                    , success: function (res) {
                        if (res.errorCode != '00000') {
                            layer.msg(res.errorMessage, {
                                offset: '15px'
                                , icon: 2
                                , time: 3000
                            });

                            return false;
                        }

                        //登入成功的提示与跳转
                        layer.msg('禁用成功!', {
                            offset: '15px'
                            , icon: 1
                            , time: 3000
                        });

                        layui.table.reload('LAY-myinvoice-manage'); //重载表格
                        layer.close(index); //执行关闭
                    }
                });
            });
        } else if (obj.event === 'enable') {
            layer.confirm('确定要启用吗？', function (index) {
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                $.ajax({
                    url: setter.baseConfig.apiHost + '/api/user/disableuser' //实际使用请改成服务端真实接口
                    , type: 'post'
                    , contentType: "application/json"
                    , data: JSON.stringify({
                        id: data.id,
                        isEnabled: 'Y'
                    })
                    , beforeSend: function (xhr) {
                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                    }
                    , success: function (res) {
                        if (res.errorCode != '00000') {
                            layer.msg(res.errorMessage, {
                                offset: '15px'
                                , icon: 2
                                , time: 3000
                            });

                            return false;
                        }

                        //登入成功的提示与跳转
                        layer.msg('启用成功!', {
                            offset: '15px'
                            , icon: 1
                            , time: 3000
                        });

                        layui.table.reload('LAY-myinvoice-manage'); //重载表格
                        layer.close(index); //执行关闭
                    }
                });
            });
        } else if (obj.event === 'downloadPdf') {//下载PDF
            let downloadFormData = {
                taskName: '下载文件',
                id: data.id,
                fileFormat: 2,
                billType: data.invoiceType
            };
            admin.popup({
                title: '下载文件'
                , area: ['60%', '60%']
                , id: 'LAY-popup-convert-ofdtopdf-download'
                , success: function (layero, index) {
                    view(this.id).render('convert/downloadform', downloadFormData).done(function () {
                        form.render(null, 'layuiadmin-form-convert-download');

                        //开启提交
                        form.on('submit(LAY-convert-download-front-submit)', function (data) {
                            var field = data.field; //获取提交的字段
                            let exportFieldObj = {};
                            let customFileNameArr = [];

                            //参数校验
                            let isCheckIssueDate = field['arr[issueDate]'] != null && field['arr[issueDate]'] == 'on';
                            let isCheckInvoiceNumber = field['arr[invoiceNumber]'] != null && field['arr[invoiceNumber]'] == 'on';
                            let isCheckEticketNumber = field['arr[eticketNumber]'] != null && field['arr[eticketNumber]'] == 'on';
                            let isCheckBuyerName = field['arr[buyerName]'] != null && field['arr[buyerName]'] == 'on';
                            let isCheckTotal = field['arr[total]'] != null && field['arr[total]'] == 'on';

                            //发票号码和电子客票号至少选择一个
                            if (!isCheckInvoiceNumber && !isCheckEticketNumber) {
                                layer.msg('发票号码和电子客票号至少选择一个!');
                                return false;
                            }

                            //构造请求
                            exportFieldObj.fileFormat = field.fileFormat;
                            if (isCheckIssueDate) {
                                customFileNameArr.push('IssueDate');
                            }
                            if (isCheckInvoiceNumber) {
                                customFileNameArr.push('InvoiceNumber');
                            }
                            if (isCheckEticketNumber) {
                                customFileNameArr.push('EticketNumber');
                            }
                            if (isCheckBuyerName) {
                                customFileNameArr.push('BuyerName');
                            }
                            if (isCheckTotal) {
                                customFileNameArr.push('Total');
                            }
                            exportFieldObj.customFileName = customFileNameArr;
                            field.exportField = exportFieldObj;

                            $.ajax({
                                url: setter.baseConfig.apiHost + '/api/convert/download' //实际使用请改成服务端真实接口
                                , type: 'post'
                                , contentType: "application/json"
                                , data: JSON.stringify(field)
                                , beforeSend: function (xhr) {
                                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                }
                                , success: function (res) {
                                    if (res.errorCode != '00000') {
                                        layer.msg(res.errorMessage, {
                                            offset: 'auto'
                                            , icon: 2
                                            , time: 3000
                                        });

                                        return false;
                                    }

                                    layer.alert('下载申请已提交，系统已启用离线下载模式，本次下载的数据将展示在【我的-我的下载】中，请注意查收！', {
                                        offset: 'auto'
                                        , icon: 1
                                    });

                                    layui.table.reload('LAY-convert-ofdtopdf-manage'); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            });
                        });

                        //取消
                        // 普通事件
                        //  2.9+ 版本可省略 attr 参数，默认读取 lay-on
                        util.on({
                            cancelConvertDownloadForm: function () {
                                console.log(this); // 当前触发事件的 DOM 元素
                                layer.close(index);
                            }
                        });
                    });
                }
            });
        } else if (obj.event === 'downloadXml') {//下载XML
            let downloadFormData = {
                taskName: '下载文件',
                id: data.id,
                fileFormat: 3,
                billType: data.invoiceType
            };
            admin.popup({
                title: '下载文件'
                , area: ['60%', '60%']
                , id: 'LAY-popup-convert-ofdtoxml-download'
                , success: function (layero, index) {
                    view(this.id).render('convert/downloadform', downloadFormData).done(function () {
                        form.render(null, 'layuiadmin-form-convert-download');

                        //开启提交
                        form.on('submit(LAY-convert-download-front-submit)', function (data) {
                            var field = data.field; //获取提交的字段
                            let exportFieldObj = {};
                            let customFileNameArr = [];

                            //参数校验
                            let isCheckIssueDate = field['arr[issueDate]'] != null && field['arr[issueDate]'] == 'on';
                            let isCheckInvoiceNumber = field['arr[invoiceNumber]'] != null && field['arr[invoiceNumber]'] == 'on';
                            let isCheckEticketNumber = field['arr[eticketNumber]'] != null && field['arr[eticketNumber]'] == 'on';
                            let isCheckBuyerName = field['arr[buyerName]'] != null && field['arr[buyerName]'] == 'on';
                            let isCheckTotal = field['arr[total]'] != null && field['arr[total]'] == 'on';

                            //发票号码和电子客票号至少选择一个
                            if (!isCheckInvoiceNumber && !isCheckEticketNumber) {
                                layer.msg('发票号码和电子客票号至少选择一个!');
                                return false;
                            }

                            //构造请求
                            exportFieldObj.fileFormat = field.fileFormat;
                            if (isCheckIssueDate) {
                                customFileNameArr.push('IssueDate');
                            }
                            if (isCheckInvoiceNumber) {
                                customFileNameArr.push('InvoiceNumber');
                            }
                            if (isCheckEticketNumber) {
                                customFileNameArr.push('EticketNumber');
                            }
                            if (isCheckBuyerName) {
                                customFileNameArr.push('BuyerName');
                            }
                            if (isCheckTotal) {
                                customFileNameArr.push('Total');
                            }
                            exportFieldObj.customFileName = customFileNameArr;
                            field.exportField = exportFieldObj;

                            $.ajax({
                                url: setter.baseConfig.apiHost + '/api/convert/download' //实际使用请改成服务端真实接口
                                , type: 'post'
                                , contentType: "application/json"
                                , data: JSON.stringify(field)
                                , beforeSend: function (xhr) {
                                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                }
                                , success: function (res) {
                                    if (res.errorCode != '00000') {
                                        layer.msg(res.errorMessage, {
                                            offset: 'auto'
                                            , icon: 2
                                            , time: 3000
                                        });

                                        return false;
                                    }

                                    layer.alert('下载申请已提交，系统已启用离线下载模式，本次下载的数据将展示在【我的-我的下载】中，请注意查收！', {
                                        offset: 'auto'
                                        , icon: 1
                                    });

                                    layui.table.reload('LAY-convert-ofdtopdf-manage'); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            });
                        });

                        //取消
                        // 普通事件
                        //  2.9+ 版本可省略 attr 参数，默认读取 lay-on
                        util.on({
                            cancelConvertDownloadForm: function () {
                                console.log(this); // 当前触发事件的 DOM 元素
                                layer.close(index);
                            }
                        });
                    });
                }
            });
        }
        else if (obj.event === 'downloadOfd') {//下载OFD
            let downloadFormData = {
                taskName: '下载文件',
                id: data.id,
                fileFormat: 1,
                billType: data.invoiceType
            };
            admin.popup({
                title: '下载文件'
                , area: ['60%', '60%']
                , id: 'LAY-popup-convert-ofdtoofd-download'
                , success: function (layero, index) {
                    view(this.id).render('convert/downloadform', downloadFormData).done(function () {
                        form.render(null, 'layuiadmin-form-convert-download');

                        //开启提交
                        form.on('submit(LAY-convert-download-front-submit)', function (data) {
                            var field = data.field; //获取提交的字段
                            let exportFieldObj = {};
                            let customFileNameArr = [];

                            //参数校验
                            let isCheckIssueDate = field['arr[issueDate]'] != null && field['arr[issueDate]'] == 'on';
                            let isCheckInvoiceNumber = field['arr[invoiceNumber]'] != null && field['arr[invoiceNumber]'] == 'on';
                            let isCheckEticketNumber = field['arr[eticketNumber]'] != null && field['arr[eticketNumber]'] == 'on';
                            let isCheckBuyerName = field['arr[buyerName]'] != null && field['arr[buyerName]'] == 'on';
                            let isCheckTotal = field['arr[total]'] != null && field['arr[total]'] == 'on';

                            //发票号码和电子客票号至少选择一个
                            if (!isCheckInvoiceNumber && !isCheckEticketNumber) {
                                layer.msg('发票号码和电子客票号至少选择一个!');
                                return false;
                            }

                            //构造请求
                            exportFieldObj.fileFormat = field.fileFormat;
                            if (isCheckIssueDate) {
                                customFileNameArr.push('IssueDate');
                            }
                            if (isCheckInvoiceNumber) {
                                customFileNameArr.push('InvoiceNumber');
                            }
                            if (isCheckEticketNumber) {
                                customFileNameArr.push('EticketNumber');
                            }
                            if (isCheckBuyerName) {
                                customFileNameArr.push('BuyerName');
                            }
                            if (isCheckTotal) {
                                customFileNameArr.push('Total');
                            }
                            exportFieldObj.customFileName = customFileNameArr;
                            field.exportField = exportFieldObj;

                            $.ajax({
                                url: setter.baseConfig.apiHost + '/api/convert/download' //实际使用请改成服务端真实接口
                                , type: 'post'
                                , contentType: "application/json"
                                , data: JSON.stringify(field)
                                , beforeSend: function (xhr) {
                                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                }
                                , success: function (res) {
                                    if (res.errorCode != '00000') {
                                        layer.msg(res.errorMessage, {
                                            offset: 'auto'
                                            , icon: 2
                                            , time: 3000
                                        });

                                        return false;
                                    }

                                    layer.alert('下载申请已提交，系统已启用离线下载模式，本次下载的数据将展示在【我的-我的下载】中，请注意查收！', {
                                        offset: 'auto'
                                        , icon: 1
                                    });

                                    layui.table.reload('LAY-convert-ofdtopdf-manage'); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            });
                        });

                        //取消
                        // 普通事件
                        //  2.9+ 版本可省略 attr 参数，默认读取 lay-on
                        util.on({
                            cancelConvertDownloadForm: function () {
                                console.log(this); // 当前触发事件的 DOM 元素
                                layer.close(index);
                            }
                        });
                    });
                }
            });
        }
    });

    //管理员管理
    table.render({
        elem: '#LAY-user-back-manage'
        , url: './res/json/useradmin/mangadmin.js' //模拟接口
        , cols: [[
            { type: 'checkbox', fixed: 'left' }
            , { field: 'id', width: 80, title: 'ID', sort: true }
            , { field: 'loginname', title: '登录名' }
            , { field: 'telphone', title: '手机' }
            , { field: 'email', title: '邮箱' }
            , { field: 'role', title: '角色' }
            , { field: 'jointime', title: '加入时间', sort: true }
            , { field: 'check', title: '审核状态', templet: '#buttonTpl', minWidth: 80, align: 'center' }
            , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
        ]]
        , text: '对不起，加载出现异常！'
    });

    //工具条
    table.on('tool(LAY-user-back-manage)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.prompt({
                formType: 1
                , title: '敏感操作，请验证口令'
            }, function (value, index) {
                layer.close(index);
                layer.confirm('确定删除此管理员？', function (index) {
                    console.log(obj)
                    obj.del();
                    layer.close(index);
                });
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '编辑管理员'
                , area: ['420px', '450px']
                , id: 'LAY-popup-myinvoice-batchupload'
                , success: function (layero, index) {
                    view(this.id).render('user/administrators/adminform', data).done(function () {
                        form.render(null, 'layuiadmin-form-admin');

                        //提交
                        form.on('submit(LAY-user-back-submit)', function (data) {
                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            //$.ajax({});
                            layui.table.reload('LAY-user-back-manage'); //重载表格
                            layer.close(index); //执行关闭 
                        });
                    });
                }
            });
        }
    });

    //角色管理
    table.render({
        elem: '#LAY-user-back-role'
        , url: './res/json/useradmin/role.js' //模拟接口
        , cols: [[
            { type: 'checkbox', fixed: 'left' }
            , { field: 'id', width: 80, title: 'ID', sort: true }
            , { field: 'rolename', title: '角色名' }
            , { field: 'limits', title: '拥有权限' }
            , { field: 'descr', title: '具体描述' }
            , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
        ]]
        , text: '对不起，加载出现异常！'
    });

    //工具条
    table.on('tool(LAY-user-back-role)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('确定删除此角色？', function (index) {
                obj.del();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '添加新角色'
                , area: ['500px', '480px']
                , id: 'LAY-popup-myinvoice-batchupload'
                , success: function (layero, index) {
                    view(this.id).render('user/administrators/roleform', data).done(function () {
                        form.render(null, 'layuiadmin-form-role');

                        //提交
                        form.on('submit(LAY-user-role-submit)', function (data) {
                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            //$.ajax({});
                            layui.table.reload('LAY-user-back-role'); //重载表格
                            layer.close(index); //执行关闭 
                        });
                    });
                }
            });
        }
    });

    exports('ofdtopdf', {})
});